package ru.slovoslovo.cropmotion;

import javax.xml.bind.JAXBContext;

import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@SuppressWarnings("rawtypes")
public abstract class JAXBSerializer {

    private Class targetClass = null;
    
    private static final Logger LOG = LoggerFactory.getLogger(JAXBSerializer.class);
    
    /**
     * JAXB variables for serialization/deserialization
     */
    private JAXBContext jaxbContext = null;
    private Marshaller jaxbMarshaller = null;
    private Unmarshaller jaxbUnmarshaller = null;
    
    public JAXBSerializer(){
    }
    
    public JAXBSerializer(Class targetClass){
        this.targetClass = targetClass;
    }
    
    protected JAXBContext getJaxbContext() {
        if (jaxbContext == null){
            try {
                jaxbContext = JAXBContext.newInstance(targetClass);
            } catch (JAXBException e) {
                LOG.error("Error creation JAXBContext, ", e);
            }
        }
        return jaxbContext;
    }

    protected void setJaxbContext(JAXBContext jaxbContext) {
        this.jaxbContext = jaxbContext;
    }

    protected Marshaller getJaxbMarshaller() {
        if (jaxbMarshaller == null){
            if (getJaxbContext() != null){
                try {
                    jaxbMarshaller = getJaxbContext().createMarshaller();
                } catch (JAXBException e) {
                    LOG.error("Error creation JAXB marshaller, ", e);
                }
            }
        }
        
        return jaxbMarshaller;
    }

    protected void setJaxbMarshaller(Marshaller jaxbMarshaller) {
        this.jaxbMarshaller = jaxbMarshaller;
    }

    protected Unmarshaller getJaxbUnmarshaller() {
        if (jaxbUnmarshaller == null){
            if (getJaxbContext() != null){
                try {
                    jaxbUnmarshaller = getJaxbContext().createUnmarshaller();
                } catch (JAXBException e) {
                    LOG.error("Error creation JAXB unmarshaller, ", e.getMessage());
                }
            }
        }        
        
        return jaxbUnmarshaller;
    }

    protected void setJaxbUnmarshaller(Unmarshaller jaxbUnmarshaller) {
        this.jaxbUnmarshaller = jaxbUnmarshaller;
    }
}
